package com.qf.mvc2203.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProductInterceptor implements HandlerInterceptor {

    /**
     * 注意，返回值 如果为 true，代表当前请求可以继续向后发送给 Controller中的handler方法
     * 如果返回false，那么当前的请求到此为止
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("pre~~~~~~");

        final long start = System.currentTimeMillis();// 开始时间戳
        // 将处理当前请求的    起始时间戳存放到当前的reuqest对象中
        // 在后续调用到postHandle方法时，会收到同一个request对象
        request.setAttribute("start",start);

        // 判断当前请求是否登录过
        final String token = request.getHeader("token");

        if (token!=null){
            return true;  // 放行当前请求，会让请求继续交给后面的 handler 处理
        }else {
            // 用户没有登录过 ，重定向到 登录页
            response.sendRedirect("/form.html");

            // 要让请求就此打住，不要再给后面的handler发送了
            return  false;

        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("post~~~~~~");

        // 如何获取处理该请求的起始时间戳
        final long start = (long) request.getAttribute("start");

        final long end = System.currentTimeMillis();

//        final String requestURI = request.getRequestURI();

        System.out.println(handler+" 执行了时长:"+(end-start));

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion~~~~~~");
    }
}
